package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    private final StringRedisTemplate stringRedisTemplate;
    private static final String FOLLOW_KEY = "follow:";
    private final IUserService iUserService;

    /**
     * 关注或取消关注
     *
     * @param followUserId 关注的用户id
     * @param isFollow     是否关注
     */
    @Override
    public void followOrUnfollow(Long followUserId, Boolean isFollow) {
        //1. 获取用户id
        UserDTO dto = UserHolder.getUser();
        if (dto == null) return;
        Long userId = dto.getId();
        String key = FOLLOW_KEY + userId;
        //2. 判断
        if (isFollow) {
            //3. 关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        } else {
            //4. 取消关注
            QueryWrapper<Follow> wrapper = new QueryWrapper<Follow>().eq("user_id", userId)
                    .eq("follow_user_id", followUserId);
            boolean isSuccess = remove(wrapper);
            if (isSuccess) {
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
    }

    /**
     * 是否关注
     *
     * @param followUserId
     * @return
     */
    @Override
    public boolean isFollow(Long followUserId) {
        UserDTO dto = UserHolder.getUser();
        if (dto == null) {
            return false;
        }
        LambdaQueryWrapper<Follow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Follow::getUserId, dto.getId())
                .eq(Follow::getFollowUserId, followUserId);
        return count(wrapper) > 0;

    }

    /**
     * 共同关注
     *
     * @param id
     * @return
     */
    @Override
    public List<UserDTO> followCommons(Long id) {
        UserDTO user = UserHolder.getUser();
        if (user == null) return Collections.emptyList();
        Long userId = user.getId();

        Set<String> userIdSet = stringRedisTemplate.opsForSet().intersect(FOLLOW_KEY + userId, FOLLOW_KEY + id);
        if (CollUtil.isEmpty(userIdSet)) return Collections.emptyList();

        List<User> users = iUserService.listByIds(userIdSet);
        if (CollUtil.isEmpty(users)) return Collections.emptyList();

       return users.stream().map(u -> BeanUtil.copyProperties(u, UserDTO.class))
                .collect(Collectors.toList());

    }
}
